package com.zwp.base.ext

import android.widget.EditText
import androidx.databinding.BindingAdapter
import androidx.lifecycle.findViewTreeLifecycleOwner
import androidx.lifecycle.lifecycleScope
import com.zwp.base.binding.BindingCommand
import kotlinx.coroutines.flow.*

@BindingAdapter(value = ["onTextChangCommand", "debounce"], requireAll = false)
fun onTextChangCommand(editText: EditText, bindingCommand: BindingCommand<String>, debounce: Long = 0) {
    editText.findViewTreeLifecycleOwner()?.lifecycleScope?.let {
        editText.textChangeFlow()
            .filter { it.isNotEmpty() } //过滤空字符
            .debounce(debounce)     // 防抖动
            .onEach { bindingCommand.execute(it.toString()) }
            .launchIn(it)
    }
}